import Cookies from 'js-cookie'

import userApi from '@/api/user'

// initial state
const getDefaultState = () => {
  return {
    userName: Cookies.get('adminUserName'),
    userInfo: Cookies.get("adminUserInfo"),
    userRoles: []
  }
}

const state = getDefaultState()

// mutations
const mutations = {
  setUserName (state, userName) {
    state.userName = userName
    Cookies.set('adminUserName', userName)
  },
  setUserInfo: (state, userInfo) => {
    state.userInfo = userInfo
    Cookies.set('adminUserInfo', userInfo)
  },
  setUserRoles: (state, roles) => {
    state.userRoles = roles
    Cookies.set('adminUserRoles', roles)
  },
  clearLogin (state) {
    Cookies.remove('adminUserName')
    Cookies.remove('adminUserInfo')
    Cookies.remove('adminUserRoles')
    Object.assign(state, getDefaultState())   // 清空state
  },
  clearRoles(state) {
    Cookies.remove("adminUserRoles")
  }
}

// actions
const actions = {
  initUserInfo ({ commit }) {
    userApi.getCurrentUser().then(re => {
      commit('setUserInfo', re.response)
    })
  },
  resetUserInfo({ commit }) {
    return new Promise(resolve => {
      commit('clearLogin')
      resolve()
    })
  }
}



export default {
  namespaced: true,
  state,
  mutations,
  actions
}
